package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.domain.User;
import com.zhentao.domain.dto.UserListDto;
import com.zhentao.service.UserService;
import com.zhentao.mapper.UserMapper;
import com.zhentao.until.AppHttpCodeEnum;
import com.zhentao.until.AppJwtUtil;
import com.zhentao.until.ResponseResult;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author 薄超轩
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-09-06 19:42:32
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Override
    public ResponseResult userLogin(User user) {
        if (user==null){
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据账号查找密码
        QueryWrapper<User> wrapper=new QueryWrapper();
        wrapper.lambda().eq(StringUtils.isNotBlank(user.getUsername()), User::getUsername, user.getUsername());
        User userOne = this.getOne(wrapper);
        if (userOne==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //给密码进行加密
        String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        System.out.println(password+"------------------------");

        //判断密码是否正确
        if (!userOne.getPassword().equals(password)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //建立一个map集合将token和用户信息返回给前端
        Map<String,Object>map=new HashMap<>(11);
        map.put("token", AppJwtUtil.getToken(userOne.getId().longValue()));
        map.put("userInfo", userOne);
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult findAll(UserListDto dto) {
        Page<User>page=new Page<>(dto.getPage(),dto.getSize());
        QueryWrapper<User>wrapper=new QueryWrapper<>();
        wrapper.lambda().eq(StringUtils.isNotBlank(dto.getName()), User::getUsername, dto.getName());
        Page<User> page1 = this.page(page, wrapper);
        return ResponseResult.okResult(page1.getRecords());
    }
}




